package utils

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

func Xor(bs []byte) (ret byte) {
	for _, v := range bs {
		ret ^= v
	}
	return ret
}

func CheckFrameBytes(bs []byte) bool {
	if len(bs) < 2 {
		return false
	}
	return Xor(bs[:len(bs)-1]) == bs[len(bs)-1]
}

func HexBytes(bs []byte) string {
	ret := "0x"
	for _, b := range bs {
		ret += fmt.Sprintf("%02x ", b)
	}
	return ret
}

type response struct {
	RespCode int         `json:"resp_code"`
	RespMsg  string      `json:"resp_msg"`
	Content  interface{} `json:"content"`
	Time     string      `json:"time"`
}

func JsonResponse(w http.ResponseWriter, statusCode int, code int, msg string, content interface{}) {
	w.Header().Set("Content-Type", "application/json")
	cstLoc := time.FixedZone("GMT", 8*60*60)
	w.WriteHeader(statusCode)
	json.NewEncoder(w).Encode(&response{
		RespCode: code,
		RespMsg:  msg,
		Content:  content,
		Time:     time.Now().In(cstLoc).Format("2006/01/02 15:04:05"),
	})
}

func Bytes2String(s []byte) string {
	ret := "["
	for i, b := range s {
		ret += fmt.Sprintf("%d", b)
		if i != len(s)-1 {
			ret += ","
		}
	}
	ret += "]"
	return ret
}
